import axios from "axios";
import store from "@/store";
import { Message, MessageBox, Loading } from "element-ui";

import { timestamp } from "./token"
import { GetToken_video } from "@/api/cadre";
// create an axios instance
const service = axios.create({
  baseURL: "", // api 的 base_url
  timeout: 120 * 1000 // request timeout
});
let loadingInstance = "";
// request interceptor
service.interceptors.request.use(
  config => {
    // console.log('请求地址', config.url);
    loadingInstance = Loading.service({
      lock: true,
      text: '拼命加载中……',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // Do something before request is sent
    // if (!sessionStorage.getItem('SSA_USERID')) {
    //   var userId = "";
    //   //设置长度，这里看需求，我这里设置了4
    //   var codeLength = 26;
    //   //设置随机字符
    //   var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
    //   //循环codeLength 我设置的4就是循环4次
    //   for (var i = 0; i < codeLength; i++) {
    //     //设置随机数范围,这设置为0 ~ 36
    //     var index = Math.floor(Math.random() * 9);
    //     //字符串拼接 将每次随机的字符 进行拼接
    //     userId += random[index];
    //   }
    //   sessionStorage.setItem('SSA_USERID', userId)
    // }


    if (!(sessionStorage.getItem('SSA_VIDEO_TOKEN') && sessionStorage.getItem('SSA_VIDEO_USERID'))) {
      // if (!sessionStorage.getItem('SSA_TOKEN')) {
      var userId = "";
      //设置长度，这里看需求，我这里设置了4
      var codeLength = 26;
      //设置随机字符
      var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
      //循环codeLength 我设置的4就是循环4次
      for (var i = 0; i < codeLength; i++) {
        //设置随机数范围,这设置为0 ~ 36
        var index = Math.floor(Math.random() * 9);
        //字符串拼接 将每次随机的字符 进行拼接
        userId += random[index];
      }
      new Promise((resolve, reject) => {
        GetToken_video(userId)
          .then((response) => {
            if (response.data.code == "200") {
              let token = response.data.data;
              sessionStorage.setItem('SSA_VIDEO_TOKEN', token)
              sessionStorage.setItem('SSA_VIDEO_USERID', userId)

              config.headers.id = userId
              config.headers.code = token
            }
            resolve();
          }).catch((error) => {
            console.log(error);
          });
      })
    }




    config.headers.timestamp = timestamp();
    config.headers.id = sessionStorage.getItem('SSA_VIDEO_USERID')
    config.headers.code = sessionStorage.getItem('SSA_VIDEO_TOKEN')





    return config;
  },
  error => {
    loadingInstance.close();
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  // response => response.data,
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  response => {
    const res = response.data;
    if (res.code !== 200) {
      if (res.code == null) {
        loadingInstance.close();
        return response.data;
      }
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.code === 401) {
        // 请自行在引入 MessageBox
        // import { Message, MessageBox } from 'element-ui'
        MessageBox.confirm(
          "你已被登出，可以取消继续留在该页面，或者重新登录",
          "确定登出",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          let areaCode = store.getters.userInfo.areaCode;
          store.dispatch("FedLogOut").then(() => {
            if (areaCode != null || areaCode != "") {
              window.location.href = "/#/login?areaCode=" + areaCode;
            } else {
              window.location.href = "/#/login";
            }
            location.reload(); // 为了重新实例化vue-router对象 避免bug
          });
        });
      } else if (res.code === 405) {
        MessageBox.confirm(
          "本用户不属于当前区域，是否需要跳转到指定区域重新登录",
          "确定跳转",
          {
            confirmButtonText: "跳转",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          window.location.href = "/#/login?areaCode=" + res.data.areaCode;
          location.reload();
        });
      } else if (res.code === 40006) {
        /*网络异常，不提示消息*/
        console.log("res.msg", res.msg)
      } else if (res.code === '0') {
        //视频接口成功code:'0' ,不提示消息
        loadingInstance.close();
        return response.data;
      } else if (res.code === 408) {

        var userId = "";
        //设置长度，这里看需求，我这里设置了4
        var codeLength = 26;
        //设置随机字符
        var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        //循环codeLength 我设置的4就是循环4次
        for (var i = 0; i < codeLength; i++) {
          //设置随机数范围,这设置为0 ~ 36
          var index = Math.floor(Math.random() * 9);
          //字符串拼接 将每次随机的字符 进行拼接
          userId += random[index];
        }
        new Promise((resolve, reject) => {
          GetToken_video(userId)
            .then((response) => {
              if (response.data.code == "200") {
                let token = response.data.data;
                sessionStorage.setItem('SSA_VIDEO_TOKEN', token)
                sessionStorage.setItem('SSA_VIDEO_USERID', userId)


              }
              resolve();
            }).catch((error) => {
              console.log(error);
            });
        })

        Message({
          message: '登录信息过期，请刷新页面',
          type: "error",
          duration: 5 * 1000
        });
      }
      else {
        console.log("res.msg:", res.msg)
        /*消息提醒*/
        Message({
          message: res.msg,
          type: "error",
          duration: 5 * 1000
        });
      }
      loadingInstance.close();
      return Promise.reject("error");
    } else {
      loadingInstance.close();
      return response.data;
    }
  },
  error => {
    loadingInstance.close();
    console.log("err" + error); // for debug
    /*消息提醒*/
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error);
  }
);

export default service;
